#!/bin/bash
# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#

echo "##########################"
echo "STARTING THE PTE CONTAINER"
echo "##########################"

TIMEOUT=120
waittime=5

function checkConfigFiles()
{
local rc=1
local starttime=$(date +%s)

while test "$(($(date +%s)-starttime))" -lt "$TIMEOUT" -a $rc -ne 0
do
    echo "Waiting for $waittime secs"
    sleep $waittime
    ls /var/hyperledger/fabric/pteconfig.tgz 2>/dev/null
    test $? -eq 0 && let rc=0
done
test $rc -ne 0 && echo "Oops ... Timed out and couldn't find the tx file , exiting" && exit 1
}

#Checking for config files needed for PTE
checkConfigFiles
tar -xzvf /var/hyperledger/fabric/pteconfig.tgz
#Copying the channel config txns
cp -r CITest/*.tx /var/hyperledger/fabric/artifacts/keyfiles/
cd $GOPATH/src/github.com/hyperledger/fabric-test/tools/PTE/CITest/scripts
CWD=$PWD/../Logs

echo "#########################################"
echo "#          STARTING THE TESTS           #"
echo "#########################################"

echo "Sending Queries"
./test_driver.sh -m {{ testcase_query }} -t {{ testcase_query }}
while ps axg | grep -vw grep | grep -w "node ./pte-execRequest.js" > /dev/null; do sleep 60; done

#Query log
echo "###########"Logs for {{ testcase_query }}"############"
cat ../Logs/{{ testcase_query }}*.log | while read line; do
    echo "$line"
done

rm -rf ../Logs/{{ testcase_query }}*.log

echo "Sending Invokes"
./test_driver.sh -m {{ testcase }} -t {{ testcase }}
while ps axg | grep -vw grep | grep -w "node ./pte-execRequest.js" > /dev/null; do sleep 60; done

#Invoke log
echo "###########"Logs for {{ testcase }}"############"
cat ../Logs/{{ testcase }}*.log | while read line; do
    echo "$line"
done
sleep 30
echo "Sending Queries"
./test_driver.sh -m {{ testcase_query }} -t {{ testcase_query }}
while ps axg | grep -vw grep | grep -w "node ./pte-execRequest.js" > /dev/null; do sleep 60; done

#Query log
echo
echo "###########"Logs for {{ testcase_query }}"############"
echo
cat ../Logs/{{ testcase_query }}*.log | while read line; do
    echo "$line"
done

echo
echo "###############"PTE REPORT"##############"
echo
cat ../../pteReport.txt | while read line; do
    echo "$line"
done

echo "#########################################"
echo "#      COMPLETED RUNNING THE TESTS      #"
echo "#########################################"
